package net.flowas.modulecart.rest.impl;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import javax.ws.rs.Consumes;
import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;

import net.flowas.modulecart.rest.CrudEndpoint;

/**
 * 
 */
public abstract class AbstractEndpoint<T> implements CrudEndpoint<T> {
	protected EntityManager entityManager = Persistence.createEntityManagerFactory("cartPU").createEntityManager();

	/*
	 * (non-Javadoc)
	 * 
	 * @see net.flowas.modulecart.rest.CrudEndpoint#create(T)
	 */
	@Override
	public T create(T entity) {
		entityManager.persist(entity);
		return entity;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see net.flowas.modulecart.rest.CrudEndpoint#deleteById(java.lang.Long)
	 */
	@Override
	public void deleteById(Long id) {
		T entity = entityManager.find(getType(), id);
		if (entity == null) {
			// return Response.status(Status.NOT_FOUND).build();
		}
		entityManager.remove(entity);
		// return Response.noContent().build();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see net.flowas.modulecart.rest.CrudEndpoint#findById(java.lang.Long)
	 */
	@Override
	public T findById(Long id) {
		String typeName = getType().getSimpleName();
		TypedQuery<T> findByIdQuery = entityManager
				.createQuery("SELECT c FROM " + typeName + " c  WHERE c.id = :entityId ORDER BY c.id", getType());
		findByIdQuery.setParameter("entityId", id);
		T entity;
		try {
			entity = findByIdQuery.getSingleResult();
		} catch (NoResultException nre) {
			entity = null;
		}
		if (entity == null) {
			// return Response.status(Status.NOT_FOUND).build();
		}
		return entity;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see net.flowas.modulecart.rest.CrudEndpoint#update(T)
	 */
	@Override
	public void update(T entity) {
		entity = entityManager.merge(entity);
	}

	protected abstract Class<T> getType();
}